package cn.stazxr.core.interceptor;

import cn.stazxr.constants.HttpConstant;
import cn.stazxr.core.TokenHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.Map;

/**
 * @author talentestors
 * @version 1.0
 * @since 2025.10.29
 **/
public class LoginInterceptor implements HandlerInterceptor {

	@Autowired
	private TokenHandler tokenHandler;
	@Autowired
	private ObjectMapper objectMapper;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//		// 1. 设置一个白名单
//		List<String> whiteList = List.of("/admin/login");
//		if (whiteList.contains(request.getServletPath())) {
//			return true;
//		}
		// 2. 如果不是白名单的请求，则进行登录校验
		// 拿到 Authorization 头部信息
		String token = request.getHeader(HttpConstant.AUTHORIZATION);
		String userName = request.getHeader("userName");
		if (token == null) {
			sendJsonResponse(response, HttpStatus.UNAUTHORIZED, HttpConstant.BAD_CREDENTIALS);
			return false;
		}
		// 3. 使用token去 Redis 中查询用户信息
		if (!tokenHandler.authToken(token, userName)) {
			sendJsonResponse(response, HttpStatus.UNAUTHORIZED, HttpConstant.BAD_CREDENTIALS);
			return false;
		}
		// 为用户续期
		tokenHandler.resetToken(token, userName);
		return true;
	}

	@SuppressWarnings("SameParameterValue")
	private void sendJsonResponse(HttpServletResponse response, HttpStatus status, String message) throws IOException {
		response.setContentType("application/json;charset=UTF-8");
		response.setStatus(status.value());
		Map<String, Object> errorBody = Map.of(
			"error", status.getReasonPhrase(),
			"message", message,
			"timestamp", System.currentTimeMillis()
		);
		response.getWriter().write(objectMapper.writeValueAsString(errorBody));
	}
}
